<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        mode="horizontal"
        :selected-keys="selectedKeys"
        @menu-item-click="doMenuClick"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="titleBar">
            <img class="logo" src="../assets/logo.jpg" />
            <div class="title">Lin-智能AI在线答题平台</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <!-- 显示用户信息，并点击跳转 -->
      <div
        v-if="loginUserStore.loginUser.id"
        class="user-info"
        @click="goToUserProfile"
      >
        <img
          class="avatar"
          :src="loginUserStore.loginUser.userAvatar"
          alt="User Avatar"
        />
        <span>{{ loginUserStore.loginUser.userName ?? "无名" }}</span>
      </div>
      <!-- 用户未登录时显示登录按钮 -->
      <div v-else>
        <a-button type="primary" href="/user/login">登录</a-button>
      </div>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "@/router/routers";
import { useRouter } from "vue-router";
import { computed, ref } from "vue";
import { userLoginUserStore } from "@/store/userStore";
import checkAccess from "@/access/checkAccess";

const loginUserStore = userLoginUserStore();
const router = useRouter();

// 当前选中的菜单项
const selectedKeys = ref(["/"]);

// 路由跳转时，自动更新选中的菜单项
router.afterEach((to) => {
  selectedKeys.value = [to.path];
});

// 展示在菜单栏的路由数组
const visibleRoutes = computed(() => {
  return routes.filter((item) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    // 根据权限过滤菜单
    if (!checkAccess(loginUserStore.loginUser, item.meta?.access as string)) {
      return false;
    }
    return true;
  });
});

// 点击菜单跳转到对应页面
const doMenuClick = (key: string) => {
  router.push({ path: key });
};

// 跳转到用户个人信息页面
const goToUserProfile = () => {
  router.push("/user/profile");
};
</script>

<style scoped>
#globalHeader {
  background-color: #fff;
}

.titleBar {
  display: flex;
  align-items: center;
}

.title {
  margin-left: 16px;
  color: black;
}

.logo {
  height: 48px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-info:hover {
  background-color: #f5f5f5;
}
.avatar {
  width: 32px;
  height: 32px;
  margin-right: 8px;
  border-radius: 50%;
}
</style>
